package cn.com.zhuxulin.info.Services;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import cn.com.zhuxulin.info.Interfaces.Parse;
import cn.com.zhuxulin.info.Utils.HttpRequest;
import cn.com.zhuxulin.info.Utils.IOUtils;
import cn.com.zhuxulin.info.Utils.ReplaceXml;

public class WeatherInfo extends DefaultHandler implements Parse {
	private static String url = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx";
	private static String xmlFileName = "/weather.xml";
	private static String xml;
	private int point;
	private String[] dates = new String[7];
	private String[][] fiveDays = new String[5][5];

	public void setCityCode(String code) throws UnsupportedEncodingException, IOException {
		InputStream inputStream = this.getClass().getResourceAsStream(xmlFileName);
		xml = ReplaceXml.replace(IOUtils.getXmlString(inputStream), "CityID", code);
	}

	public Object[] getWeather() throws Exception {

		SAXParser parser = null;
		try {
			parser = SAXParserFactory.newInstance().newSAXParser();
			parser.parse(HttpRequest.doPostForInputStream(url, xml), this);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new Object[] { dates, fiveDays };
	}

	public void characters(char[] ch, int start, int length) throws SAXException {
		if (point > 0 && point <= 7) {
			dates[point - 1] = new String(ch, 0, length);
			// System.out.println(dates[point-1]);
		}
		if (point > 7) {
			fiveDays[(point - 8) / 5][(point - 8) % 5] = new String(ch, 0, length);
			// System.out.println("fourDays["+((point-8)/5)+"]["+((point-8)%5)+"]"+fourDays[(point-8)/5][(point-8)%5]);
		}
	}

	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		if (qName.equals("string")) {
			point++;
		}
	}

	public String parse(String xml1) {
		SAXParser parser = null;
		try {
			parser = SAXParserFactory.newInstance().newSAXParser();
			parser.parse(HttpRequest.doPostForInputStream(url, xml), this);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
